﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Marbles.Core.Content.Sites;
using Ionic.Zip;
using System.Web;

namespace Marbles.Core.Site
{
    public class FileSystem
    {

        public void Backup(string filename, string directory, bool toplevelonly)
        {
            FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            Backup(fs, directory, toplevelonly);
            fs.Flush();
            fs.Close();
        }

        public void Backup(HttpResponse response, string filename, string directory, bool toplevelonly)
        {
            response.Clear();
            response.ContentType = "application/zip";
            response.AddHeader("content-disposition", string.Format("attachment;filename={0}.zip", filename));
            Backup(response.OutputStream, directory, toplevelonly);
            response.Flush();
            response.End();
        }

        public void Backup(System.IO.Stream stream, string directory, bool toplevelonly)
        {
            string path = HttpContext.Current.Server.MapPath(directory);

            using (ZipFile zip = new ZipFile())
            {
                foreach (string filename in Directory.GetFiles(path, "*.*", (toplevelonly) ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories))
                {
                    FileInfo info = new FileInfo(filename);
                    zip.AddFile(filename, GetDirectoryPath(info));
                }

                zip.Save(stream);
            }
        }

        private string GetDirectoryPath(FileInfo info)
        {
            DirectoryInfo dir = info.Directory;
            string path = "";
            try
            {
                while (dir != null)
                {
                    path = "/" + dir.Name + path;
                    dir = dir.Parent;
                }
            }
            catch { }

            path += "/";
            return path;
        }

    }
}
